package com.daxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.util.DateUtil;
import com.daxt.common.util.SdkUtil;
import com.daxt.mapper.sys.DeptMapper;
import com.daxt.model.dic.DicDocFrom;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.service.accept.vo.DicDocFroms;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.base.vo.Dept;
import com.daxt.service.DeptService;
import com.sxlq.dmapi.model.Org;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Scheduled(cron = "0 0 23 ? * SUN")
    @Async("cloudExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void syncDeptInfoNewScheduled(){
        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
            String nowTime= DateUtil.getCurrentTime(DateUtil.DateFormat.YYYY_MM_DD_HH_mm_ss);
            String subTime=DateUtil.subDayOfMonth(nowTime, DateUtil.DateFormat.YYYY_MM_DD_HH_mm_ss,7);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = format.parse(subTime);
                syncDeptInfoNew(date);
            }catch (ParseException e){
                e.printStackTrace();
            }
        }
    }

    public void syncDeptInfoNew(Date date){
        //获取全部外部部门信息
        List<Org> listDept = SdkUtil.getSdkDeptAll(date);
        //若没有数据则直接中断
        if(listDept.size()<=0){
            System.out.println("===========没有要更新的外部部门信息========");
            return;
        }
        String headDeptPids=null;
        List<String> twoDeptPids=new ArrayList<>();
        //一级部门
        for(int i=0;i<listDept.size();i++) {
            Org org = listDept.get(i);
            //过滤被禁用的部门信息
            if ("2".equals(org.getDeptstatus())) continue;
            if("1".equals(org.getDeptrank())){
                Dept dept=orgTransitionDept(org);
                dept.setSort(1);
                saveOrUpdate(dept);

                Dept deptHead = getById(90000);
                if (deptHead == null) {
                    //新建集团总部  二级目录
                    deptHead = new Dept();
                    deptHead.setId(90000L);
                    deptHead.setParentId(dept.getId());
                    deptHead.setDeptName("集团总部");
                    deptHead.setSort(0);
                    deptHead.setPDeptCode(dept.getDeptCode());
                    deptHead.setDeptCode("LQZDY00001");
                    deptHead.setPids(dept.getPids() + "LQZDY00001/");
                    saveOrUpdate(deptHead);
                }
                headDeptPids=deptHead.getPids();
            }
        }

        // 二、三、四、五级部门
        for(int i=0;i<listDept.size();i++){
            Org org= listDept.get(i);
            //过滤被禁用的部门信息
            if("2".equals(org.getDeptstatus())) continue;

            Dept dept=orgTransitionDept(org);
            //二级部门
            if("2".equals(org.getDeptrank())){
                String fullname=org.getFullname();
                //集团总部的下的各个部门
                if(!fullname.endsWith("公司")){
                    twoDeptPids.add(dept.getPids());

                    dept.setParentId(90000L);
                    dept.setPDeptCode("LQZDY00001");
                    dept.setPids(headDeptPids+dept.getDeptCode()+"/");


                }
            }
            saveOrUpdate(dept);
        }

        //处理集团总部下部门的子集部门
        QueryWrapper<Dept> deptQueryWrapper=new QueryWrapper<>();
        for (int i=0;i<twoDeptPids.size();i++){
            String pids= twoDeptPids.get(i);
            deptQueryWrapper.like("pids",pids);
            List<Dept> deptList = deptMapper.selectList(deptQueryWrapper);
            String[] sArr = pids.split("/");
            String pidsNew = sArr[0] + "/LQZDY00001" + "/" + sArr[1]+"/";
            for (int j=0;j<deptList.size();j++){
                Dept dept = deptList.get(j);
                String pidsOld = dept.getPids();
                dept.setPids(pidsOld.replace(pidsOld,pidsNew));
                deptMapper.updateById(dept);
            }
        }


        //处理被禁用的公司
        List<String> noIds=new ArrayList<>();
        for(int i=0;i<listDept.size();i++){
            Org org= listDept.get(i);
            if("1".equals(org.getDeptstatus())) continue;
            noIds.add(org.getOrgId());
        }
        if(noIds.size()>0){
            deptMapper.deleteBatchIds(noIds);
        }
    }


    public List<Dept> getSourceDept(UserInfo loginUser) {

        String role= loginUser.getRole();
        String deptId = loginUser.getDeptId();

        QueryWrapper<Dept> wrapper=new QueryWrapper<>();

        if(RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)){//路桥
            wrapper.eq("parentId","1");
            wrapper.in("deptName","集团总部","离隰公司");
        }else if(RedisUtil.isAppoint(VersionsMarkType.VERSIONS_6)) {//阳高
            wrapper.eq("parentId","0");
            wrapper.eq("deptName","阳高县行政审批局");
        }


        //普通用户只能，查看自己本公司的数据，
        if("admin".equals(loginUser.getUsername()) || "超级管理员".equals(role) ){

        }else{
            wrapper.eq("fondsId",loginUser.getFondsId());
            List<Dept> deptList = deptMapper.getAllParentDept(Long.parseLong(deptId));
            if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
                if(deptList.size()<=1){
                    wrapper.eq("deptName",deptList.get(0).getDeptName());
                }else{
                    wrapper.eq("deptName",deptList.get(1).getDeptName());
                }
            }else{
                wrapper.eq("deptName",deptList.get(0).getDeptName());
            }
        }

        //List<String> listDeptName=new ArrayList();
        //listDeptName.add("集团总部");//来源部门
        //listDeptName.add("离隰公司");//来源部门
        //wrapper.in("deptName",listDeptName);
        List<Dept> deptList=deptMapper.selectList(wrapper);
        List<DicDocFroms> dicDocFromList1=new ArrayList<>();
        dicDocFromList1.add(new DicDocFroms(DicDocFrom.FROM_2.getKey(),DicDocFrom.FROM_2.getValue(),"件"));//添加来源类型  离隰OA
        dicDocFromList1.add(new DicDocFroms(DicDocFrom.FROM_4.getKey(),DicDocFrom.FROM_4.getValue(),"卷"));//添加来源类型  离隰质保资料

        List<DicDocFroms> dicDocFromList2=new ArrayList<>();
        dicDocFromList2.add(new DicDocFroms(DicDocFrom.FROM_5.getKey(),DicDocFrom.FROM_5.getValue(),"件"));//添加来源类型  集团总部OA

        List<DicDocFroms> dicDocFromList3=new ArrayList<>();
        dicDocFromList3.add(new DicDocFroms(DicDocFrom.FROM_6.getKey(),DicDocFrom.FROM_6.getValue(),"件"));//添加来源类型  阳高政务审批系统
        for(Dept dept:deptList){
            if(dept.getDeptName().equals("离隰公司")){
                dept.setDicDocFromList(dicDocFromList1);
            }else if(dept.getDeptName().equals("集团总部")){
                dept.setDicDocFromList(dicDocFromList2);
            }else if(dept.getDeptName().equals("阳高县行政审批局")){
                dept.setDicDocFromList(dicDocFromList3);
            }
        }

        return deptList;
    }

    private Dept orgTransitionDept(Org org){
        Dept dept=new Dept();
        dept.setId(Long.parseLong(org.getOrgId()));
        dept.setDeptName(org.getOrgName());
        dept.setExtId(org.getOrgId());
        dept.setPids(org.getPids());
        dept.setDeptCode(org.getDeptcode());
        dept.setPDeptCode(org.getPdeptcode());
        dept.setParentId(Long.parseLong(org.getPid()));
        if(StringUtils.isEmpty(org.getNum())){
            dept.setSort(0);
        }else {
            dept.setSort(Integer.parseInt(org.getNum()));
        }

        return dept;
    }

}
